package com.invengo.module_check.ui.fragment.remove;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.invengo.library_db.entity.module_check.BookBean;
import com.invengo.library_rfid.classify.AnalyzeImpl;
import com.invengo.library_rfid.classify.RFIDCallBackListener;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.BR;
import com.invengo.module_check.R;
import com.invengo.module_check.data.repsitory.business.BusinessRepsitory;
import com.invengo.module_check.ui.fragment.remove.item.RemoveOldItemViewModel;

import java.util.List;
import java.util.stream.Collectors;

import java8.util.stream.StreamSupport;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.ItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class RemoveOldViewModel extends BaseViewModel<BusinessRepsitory> {
    public RFIDCallBackListener rfidService = new RFIDCallBackListener(AnalyzeImpl.TO_BOOK, tagInfo -> onScanResult(tagInfo), state -> isReading.set(state));
    public BindingRecyclerViewAdapter adapter = new BindingRecyclerViewAdapter();
    public ObservableList<RemoveOldItemViewModel> bookItemList = new ObservableArrayList<>();
    public ItemBinding<RemoveOldItemViewModel> bookitemBinding = ItemBinding.of(BR.viewModel, R.layout.item_remove_old);

    public RemoveOldViewModel(@NonNull Application application) {
        super(application, BusinessRepsitory.getInstance());
        registerRFID(rfidService);
    }

    private void onScanResult(TagInfo tagInfo) {
        switch (tagInfo.getRfidModel()) {
            case TID:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
//                    getShelfByTid(tagInfo.getTag());
                } else
                    getBookByTid(tagInfo.getTag());
                break;
            case EPC:
            case U_DATA:
                if (tagInfo.getScanModel() == AnalyzeImpl.TO_SHELF) {
//                    getShelfByCode(tagInfo.getTag());
                } else
                    getBookByCode(tagInfo.getTag());
                break;
        }
    }

    public UIChangeObservable ui = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent<List<BookBean>> removeBookEvent = new SingleLiveEvent<>();
    }

    /**
     * 获取position的方式有很多种,indexOf是其中一种，常见的还有在Adapter中、ItemBinding.of回调里
     *
     * @return
     */
    public int getPosition(ItemViewModel item) {
        return bookItemList.indexOf(item);
    }

    public void onItemRemove(ItemViewModel item) {
        int position = bookItemList.indexOf(item);
        bookItemList.remove(position);
        adapter.notifyDataSetChanged();
        ToastUtils.showShort("删除成功");
    }

    /**
     * 按Tid查询书本
     *
     * @param tid 标签
     */
    private void getBookByTid(String tid) {
        model.getBookByTid(tid)
                .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                .subscribe(bookBean -> {
                    addItem(bookBean);
                });
    }


    /**
     * 按Tid查询书本
     *
     * @param code 标签
     */
    private void getBookByCode(String code) {
        model.getBookByCode(code)
                .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                .subscribe(bookBean -> addItem(bookBean));
    }

    public void getBooksByKeyword(String keyword) {
        model.getBookByKeyword(keyword, 1, 1)
                .compose(RxUtils.applySchedulersIO(getLifecycleProvider(), this))
                .subscribe(bookBeans -> {
                    for (BookBean bookBean : bookBeans) {
                        addItem(bookBean);
                    }
                });
    }

    /**
     * 添加项目
     *
     * @param bean 豆
     */
    private void addItem(BookBean bean) {
        bookItemList.add(new RemoveOldItemViewModel(this, bean));
    }

    public BindingCommand<String> searchBookCommand = new BindingCommand<>(s -> {
        getUC().getHideKeyboardEvent().call();
        getBooksByKeyword(s);
    });
    private String keyword = "";
    public BindingCommand<String> textChange = new BindingCommand<>(s -> {
        keyword = s;
    });

    public BindingCommand searchBook = new BindingCommand<>(() -> {
        getUC().getHideKeyboardEvent().call();
        if (TextUtils.isEmpty(keyword)) {
            ToastUtils.showShort("请先输入需要查找的数据");
            return;
        }
        getBooksByKeyword(keyword);
    });

    /**
     * 单层下架清理
     */
    public BindingCommand cleanAllBooks = new BindingCommand(() -> {
        cleanRFIDCache();
        bookItemList.clear();
    });

    public BindingCommand saveCommand = new BindingCommand(() -> {
        ui.removeBookEvent.postValue(getMatchBooks());
    });

    public List<BookBean> getMatchBooks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return bookItemList.stream()
                    .map(viewModel -> viewModel.book.getValue())
                    .collect(Collectors.toList());
        }else{
            return StreamSupport.stream(bookItemList)
                    .map(viewModel -> viewModel.book.getValue())
                    .collect(java8.util.stream.Collectors.toList());
        }
    }

    public void insertBookDeleteLogs(List<BookBean> beans) {
        if (bookItemList.size() == 0) {
            ToastUtils.showShort("请先扫描图书");
            return;
        }
        model.removeOld(beans)
                .compose(RxUtils.applySchedulersToast(getLifecycleProvider(), this))
                .subscribe(updateResult -> {
                    cleanRFIDCache();
                    getUC().getFinishEvent().call();
                });
    }
}
